const express = require('express');
const Exercise = require('../models/Exercise');

const router = express.Router();

// 获取题目列表
router.get('/', async (req, res) => {
  try {
    const { type, difficulty, page = 1, limit = 10 } = req.query;
    
    // 构建查询条件
    const query = { isActive: true };
    if (type) query.type = type;
    if (difficulty) query.difficulty = difficulty;

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 查询题目
    const exercises = await Exercise.find(query)
      .select('-__v')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Exercise.countDocuments(query);

    res.json({
      success: true,
      data: {
        exercises,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      }
    });
  } catch (error) {
    console.error('获取题目列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取题目列表失败'
    });
  }
});

// 获取单个题目详情
router.get('/:id', async (req, res) => {
  try {
    const exercise = await Exercise.findById(req.params.id);

    if (!exercise || !exercise.isActive) {
      return res.status(404).json({
        success: false,
        message: '题目不存在'
      });
    }

    res.json({
      success: true,
      data: exercise
    });
  } catch (error) {
    console.error('获取题目详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取题目详情失败'
    });
  }
});

// 获取随机题目
router.get('/random/one', async (req, res) => {
  try {
    const { type, difficulty } = req.query;
    
    const query = { isActive: true };
    if (type) query.type = type;
    if (difficulty) query.difficulty = difficulty;

    const count = await Exercise.countDocuments(query);
    if (count === 0) {
      return res.status(404).json({
        success: false,
        message: '没有找到符合条件的题目'
      });
    }

    const random = Math.floor(Math.random() * count);
    const exercise = await Exercise.findOne(query).skip(random);

    res.json({
      success: true,
      data: exercise
    });
  } catch (error) {
    console.error('获取随机题目错误:', error);
    res.status(500).json({
      success: false,
      message: '获取随机题目失败'
    });
  }
});

module.exports = router;
